use scopeguard::defer;

use bc_base::{
    self, BlockHeight, BlockId, PublicKeyHashBytes,
    constants::{ALICE_PUBLIC_KEY_HASH, GENESIS_BLOCK_ID},
};

use tests::common;

#[tokio::test]
async fn create_block() {
    let (test_env, tmp_dir) = common::setup("create_block", false, None, false).await;
    defer! {
        tmp_dir.close().unwrap();
    };

    // do test here
    {
        let prev_block_hash = BlockId::from_hex_str(GENESIS_BLOCK_ID).unwrap();
        let block_height: BlockHeight = 1;
        let miner_pubkey_hash = PublicKeyHashBytes::from_hex_str(ALICE_PUBLIC_KEY_HASH).unwrap();
        let (block_id, _) =
            common::local::create_block_only_contain_coinbase_and_add_to_blockchain(
                test_env.bc_manager.clone(),
                &prev_block_hash,
                block_height,
                &miner_pubkey_hash,
            )
            .await;

        let bc_manager = test_env.bc_manager.lock().await;
        assert_eq!(bc_manager.block_number().await, 2);
        assert_eq!(bc_manager.transaction_number().await, 2);
        assert_eq!(bc_manager.read_best_height().await, block_height);
        assert_eq!(
            bc_manager.read_latest_block_id_in_best_chain().await,
            block_id
        );

        bc_manager.dump_all_block().await;
    }

    common::teardown(test_env).await;
}
